﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Domain.Repositories;
using Abp.ObjectMapping;
using AutoMapper.QueryableExtensions;
using FwProject.ManagerConfig.Dto;
using Microsoft.EntityFrameworkCore;

namespace FwProject.ManagerConfig
{
    public class ConfigInfoAppService: FwProjectAppServiceBase, IConfigInfoAppService
    {
        public readonly IRepository<ConfigInfo, Guid> _repositoryConfigInfo;
        public IGuidGenerator _guid { get; set; }
        public IObjectMapper _map { get; set; }

        public ConfigInfoAppService(IRepository<ConfigInfo, Guid> repositoryConfigInfo)
        {
            _repositoryConfigInfo = repositoryConfigInfo;
            _guid = SequentialGuidGenerator.Instance;
        }

        public async Task<Guid> Create(ConfigInfoInput input)
        {
            var usermodel = await GetCurrentUserAsync();
            var model = _map.Map<ConfigInfo>(input);
            model.Id = _guid.Create();
            model.FactoryinfoId = usermodel.FactoryinfoId.Value;
            model.RegisterUserId = usermodel.Id;
            model.RegisterDate = DateTime.Now;
            return await _repositoryConfigInfo.InsertAndGetIdAsync(model);
        }

        public async Task Update(Guid id,ConfigInfoInput input)
        {
            var model = await _repositoryConfigInfo.GetAsync(id);
            model = _map.Map(input,model);
            await _repositoryConfigInfo.UpdateAsync(model);
        }

        public async Task Delete(Guid id)
        {
            var model = await _repositoryConfigInfo.GetAsync(id);
            await _repositoryConfigInfo.DeleteAsync(model);
        }

        public async Task<ConfigInfoDto> GetByIdAsync(Guid id)
        {
            var model = await _repositoryConfigInfo.GetAsync(id);
            return _map.Map<ConfigInfoDto>(model);
        }

        public async Task<ConfigInfoDto> GetListAsync()
        {
            var user = await GetCurrentUserAsync();
            ConfigInfoDto data = new ConfigInfoDto();
            var model = _repositoryConfigInfo.GetAll().Where(o=>o.FactoryinfoId==user.FactoryinfoId.Value).FirstOrDefault();
            if (model!=null)
            {
                data= _map.Map<ConfigInfoDto>(model);
            }

            return data;
        }
    }
}
